const util = require('../../../utils/util.js');

Page({
  data: {
    contactList: []
  },

  onLoad() {
    this.loadContactList();
  },

  loadContactList() {
    // 模拟数据，实际应从API获取
    const mockContacts = [
      {
        id: 1,
        name: '李女士',
        relation: '女儿',
        phone: '13912345678',
        address: '浙江省杭州市西湖区',
        avatar: 'https://dummyimage.com/200x200/FF69B4/fff.png&text=女儿',
        isPrimary: true
      },
      {
        id: 2,
        name: '张先生',
        relation: '儿子',
        phone: '13887654321',
        address: '浙江省杭州市余杭区',
        avatar: 'https://dummyimage.com/200x200/4A90E2/fff.png&text=儿子',
        isPrimary: false
      }
    ];

    this.setData({
      contactList: mockContacts
    });
  },

  onCall(e) {
    const phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone
    }).catch(() => {
      util.showToast('拨号失败');
    });
  },

  onEdit(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/mine/emergency-contact/edit?id=${id}`
    });
  },

  onDelete(e) {
    const id = e.currentTarget.dataset.id;
    const contact = this.data.contactList.find(item => item.id === id);
    
    util.showConfirm(`确定要删除紧急联系人"${contact.name}"吗？`).then(confirm => {
      if (confirm) {
        // 实际应调用API删除
        const newList = this.data.contactList.filter(item => item.id !== id);
        this.setData({
          contactList: newList
        });
        util.showToast('删除成功', 'success');
      }
    });
  },

  onAdd() {
    if (this.data.contactList.length >= 3) {
      util.showToast('最多可添加3位紧急联系人');
      return;
    }
    
    wx.navigateTo({
      url: '/pages/mine/emergency-contact/edit'
    });
  },

  onPullDownRefresh() {
    this.loadContactList();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 500);
  }
})

